package com.coocaa.typhoon.api.config.nacosjasypt;

import com.ulisesbocchio.jasyptspringboot.EncryptablePropertyResolver;
import org.jasypt.encryption.StringEncryptor;

/**
 * @author bijiahao
 * @date : 2025/9/16 16:50
 * @description
 */
public class MultiKeyPropertyResolver implements EncryptablePropertyResolver {

    private final StringEncryptor primaryEncryptor;
    private final StringEncryptor secondaryEncryptor;

    public MultiKeyPropertyResolver(StringEncryptor primary, StringEncryptor secondary) {
        this.primaryEncryptor = primary;
        this.secondaryEncryptor = secondary;
    }

    @Override
    public String resolvePropertyValue(String value) {
        if (value != null && value.startsWith("ENC(") && value.endsWith(")")) {
            String encryptedValue = value.substring(4, value.length() - 1);
            // 默认解密器
            return primaryEncryptor.decrypt(encryptedValue);
        }
        if (value != null && value.startsWith("ENC2(") && value.endsWith(")")) {
            String encryptedValue = value.substring(5, value.length() - 1);
            // 第二解密器
            return secondaryEncryptor.decrypt(encryptedValue);
        }
        return value;
    }

}
